source(here::here("R/00_setup.R"))
d_baseline = read_csv(here("data/precinct_baseline.csv"), show_col_types=FALSE)
model = read_rds(here("data/election_model.rds"))

# compute S-V curve ------

natl_baseline = with(d_baseline, log(sum(ndv)) - log(sum(nrv)))

# matrix of logit D vote shares
m_ldvs = do.call(rbind, map(cli_progress_along(state.abb), function(i) {
  abbr = state.abb[i]
  d_st = filter(d_baseline, state == abbr)
  plans = load_50state_plans(abbr)
  part_dvs(plans, d_st, ndv, nrv) |>
    qlogis() |>
    matrix(ncol=5001)
}))

# compute SVC
natl_shifts = seq(-1, 1, by=0.02)
svc = map_dfr(cli_progress_along(natl_shifts), function(i) {
  s = natl_shifts[i]
  seats = colSums(model$prob_win_logit(m_ldvs + s))
  tibble(shift = s,
         draw = 1:5000,
         seats_enac = seats[1],
         seats = seats[-1])
})


# competitiveness
d_comp = tibble(draw = rep(1:5000, each=435),
                dem = plogis(as.numeric(m_ldvs[, -1]))) |>
  mutate(dem_bin = round(dem*20)/20) |>
  group_by(draw, dem_bin) |>
  summarize(n_dem = n())
d_comp_enac = tibble(dem = plogis(m_ldvs[, 1])) |>
  mutate(dem_bin = round(dem*20)/20) |>
  group_by(dem_bin) |>
  summarize(n_dem = n())

# responsiveness
d_resp = svc |>
  group_by(draw) |>
  mutate(natl = plogis(natl_baseline + shift),
         dseats_enac = (seats_enac - lag(seats_enac)) / (natl - lag(natl)) / 100,
         dseats = (seats - lag(seats)) / (natl - lag(natl)) / 100) |>
  ungroup() |>
  drop_na()
idx_50 = with(d_resp, which(abs(natl - 0.5) == min(abs(natl - 0.5))))


# figures -------

rlang::check_installed("ggrastr")

d_enac = svc |>
  filter(draw == 1) |>
  mutate(natl = plogis(natl_baseline + shift))
sv_enac = approxfun(d_enac$natl, d_enac$seats_enac)
vs_enac = approxfun(d_enac$seats_enac, d_enac$natl)

d_vote_maj_sims = svc |>
  group_by(draw) |>
  summarize(d_vote_maj = approx(seats, plogis(natl_baseline + shift), 218)[[2]]) |>
  pull()

list(d_seats_50 = sv_enac(0.5),
     r_seats_50 = 435 - sv_enac(0.5),
     d_vote_maj = vs_enac(218),
     r_vote_maj = 1 - vs_enac(218),
     d_vote_maj_sim = median(d_vote_maj_sims),
     resp_50_enac = d_resp$dseats_enac[idx_50[1]],
     resp_50_mean = mean(d_resp$dseats[idx_50]),
     tossup_sim = median(with(d_comp, n_dem[dem_bin == 0.5])),
     tossup_enac = with(d_comp_enac, n_dem[dem_bin == 0.5])
) |>
  write_json(here("paper/stats_svc.json"), pretty=TRUE, auto_unbox=TRUE, digits=6)




p1 = ggplot(d_comp, aes(dem_bin, n_dem)) +
  geom_col(aes(fill=model$prob_win_natl(dem_bin)), width=0.045,
           data=d_comp_enac, color="#000000aa", lwd=0.1) +
  stat_slabinterval(fatten_point=1, interval_size_range=c(0.5, 1)) +
  scale_x_continuous("Average Democratic district vote share",
                     labels=percent, breaks=seq(0, 1, 0.1),
                     expand=c(0, 0), minor_breaks=seq(0, 1, 0.025)) +
  scale_fill_party_c() +
  labs(y="Number of seats") +
  guides(fill="none") +
  annotate("text", x = 0.47, y = 65, label = "Non-partisan\nsimulations", hjust = 0, size = 3) +
  annotate("text", x = 0.32, y = 45, label = "Enacted plan", hjust = 1, size = 3, color = "#A0442C") +
  coord_cartesian(xlim=c(0.075, 0.975), ylim=c(0, 70), expand=F) +
  theme_bw(base_size=10, base_family="Arial") +
  theme(panel.grid.minor.x = element_blank(),
        panel.grid.major.x = element_blank())


xl <- c(0.45, 0.55)
yl <- c(175, 260)

lab_seg = tribble(~x, ~y,
                  0.499, sv_enac(0.5),
                  0.498, sv_enac(0.5),
                  0.498, 218,
                  0.499, 218)

p3 = ggplot(svc, aes(plogis(natl_baseline + shift), seats)) +
  geom_texthline(label="Majority", yintercept=218, hjust=0.92,
                 size=2.5, linewidth=0.25) +
  geom_vline(xintercept=0.50, lwd=0.25, color ='black') +
  ggrastr::rasterize(
    geom_line(aes(group=draw), color="black", alpha=0.09, lwd=0.005),
    dpi=400) +
  ggrastr::rasterize(
    geom_line(aes(1 - plogis(natl_baseline + shift), 435 - seats, group=draw),
              color="black", alpha=0.09, lwd=0.005),
    dpi=400) +
  geom_line(aes(y=seats_enac), data=filter(svc, draw==1),
            color=ggredist$partisan[14], lwd=1.0) +
  geom_line(aes(1 - plogis(natl_baseline + shift), y=435 - seats_enac),
                data=filter(svc, draw==1),
                color=ggredist$partisan[2], lwd=1.0, lty="81") +
  geom_path(aes(x, y), data=lab_seg, lwd=0.6) +
  annotate("text", x=0.472, y=180, hjust=0, color="#666666",
           label="Dem., Non-partisan baseline", size=2.5) +
  annotate("text", x=0.528, y=255, hjust=1, color="#666666",
           label="Rep., Non-partisan baseline", size=2.5) +
  annotate("text", x=0.498, y=218/2 + sv_enac(0.5)/2, hjust=1.1,
           label="Partisan bias", size=2.7) +
  annotate("segment", x=0.520, y=205, xend=vs_enac(218), yend=218,
           arrow=arrow(type="closed", length=unit(0.015, "npc"), angle=25)) +
  annotate("text", x=0.521, y=205, hjust=0.5, vjust=1.3, lineheight=0.9,
           label=str_c(percent(vs_enac(218), 0.1),
                       " vote share needed\nto win a majority"), size=2.7) +
  scale_x_continuous("National vote share", labels=percent, breaks=seq(0, 1, 0.01)) +
  scale_y_continuous("Seats won", breaks=seq(0, 430, by=10),
                     sec.axis=sec_axis(trans=~./435, labels=label_percent(1),
                                       breaks=seq(0, 1, 0.02))) +
  coord_cartesian(xlim = xl, ylim = yl, expand=FALSE) +
  theme_bw(base_size=10, base_family="Arial") +
  theme(plot.margin=margin(4, 9, 0, 1),
        panel.grid.minor.x = element_blank())




ggsave(here("paper/figures/competitiveness.pdf"), plot=p1,
       width=4, height=3.25, device=cairo_pdf)


ggsave(here("paper/figures/seats_votes.pdf"), plot=p3,
       width=4, height=3.25, device=cairo_pdf)


# Appendix:

ggplot(d_resp, aes(natl, dseats)) +
  ggrastr::rasterize(
    geom_line(aes(group=draw), alpha=0.02, lwd=0.1),
    dpi=300) +
  geom_textline(aes(y=dseats_enac), data=filter(d_resp, draw==1),
                label="Dem., Enacted", size=2.5, hjust=0.46, vjust=1.2,
                color=ggredist$partisan[14], linewidth=0.65) +
  geom_vline(xintercept = 0.5, color = 'black', lwd=0.25) +
  scale_x_continuous("National Democratic vote share", labels=percent, breaks=seq(0, 1, 0.1),
                     expand=c(0, 0), minor_breaks=seq(0, 1, 0.025)) +
  scale_y_continuous("Responsiveness\n(Democratic seats per 1pp voteshare)", breaks=0:11,
                     expand=expansion(mult=c(0, 0.02))) +
  theme_bw(base_size=10, base_family="Arial")

ggsave(here("paper/figures/responsiveness.pdf"),
       width=4, height=3, device=cairo_pdf)
